#!/bin/bash
# 简化版 Oracle 导入脚本 - 使用相对路径创建表空间

# 设置变量
ORACLE_USER="system"
ORACLE_PASS="Yuangu#19c"
PDB_NAME="xe"
DMP_FILE="/share/kj.dmp"
LOG_FILE="/share/import.log"
TARGET_USER="KJ"
TARGET_PASS="Kj#yuangu2025"

echo "开始 Oracle 简化导入流程..."

# 1. 连接到 PDB 并创建表空间和用户
echo "步骤1: 创建表空间和用户..."
sqlplus -s ${ORACLE_USER}/${ORACLE_PASS}@${PDB_NAME} << EOF
-- 切换到 PDB xe
ALTER SESSION SET CONTAINER = xe;

-- 查看现有数据文件路径（仅供参考）
SELECT file_name FROM dba_data_files WHERE ROWNUM <= 3;

-- 创建 KJ 表空间（使用简化路径）
CREATE TABLESPACE KJ 
DATAFILE 'kj01.dbf' SIZE 500M 
AUTOEXTEND ON NEXT 50M MAXSIZE UNLIMITED;

-- 创建 KJ 用户
CREATE USER KJ IDENTIFIED BY "${TARGET_PASS}"
DEFAULT TABLESPACE KJ
TEMPORARY TABLESPACE TEMP;

-- 授予权限
GRANT CONNECT, RESOURCE TO KJ;
GRANT CREATE VIEW TO KJ;
ALTER USER KJ QUOTA UNLIMITED ON USERS;
ALTER USER KJ QUOTA UNLIMITED ON KJ;

-- 验证创建结果
SELECT tablespace_name FROM dba_tablespaces WHERE tablespace_name = 'KJ';
SELECT username FROM dba_users WHERE username = 'KJ';
SELECT username, tablespace_name, max_bytes FROM dba_ts_quotas WHERE username = 'KJ';

EXIT;
EOF

# 检查表空间和用户创建是否成功
if [ $? -ne 0 ]; then
    echo "错误: 表空间或用户创建失败，请检查上面的错误信息"
    exit 1
fi

echo "步骤2: 执行数据导入..."
imp ${ORACLE_USER}/${ORACLE_PASS}@${PDB_NAME} file=${DMP_FILE} fromuser=KJ touser=KJ ignore=y log=${LOG_FILE}

echo "导入完成，日志文件: ${LOG_FILE}"
echo "可以使用以下命令查看导入的表:"
echo "sqlplus ${TARGET_USER}/${TARGET_PASS}@${PDB_NAME}"
echo "SQL> SELECT table_name FROM user_tables ORDER BY table_name;"
echo "SQL> SELECT COUNT(*) FROM user_tables;"